import {dataSource} from '../config/database';
import {md5} from 'js-md5';
import {userEntity} from '../entity/User.entity';
import Result from '../vo/result';
import {ResultCode, ResultCodeMessages} from '../enums/resultCode';
import {generateToken} from '../jwt/jwtService';
import {setRedis} from '../redis/Redis';
import {userPageQuery} from '../controllers/UserController/User.dto';


const tableRepository = dataSource.getRepository(userEntity);
export const getUserByIdService = async (userId: number) => {
  const user = await tableRepository.findOneBy({userId: userId});
  if (!user) {
    return Result.fail(ResultCode.USER_NOT_EXIST, ResultCodeMessages[ResultCode.USER_NOT_EXIST]);
  }
  return Result.success(user);
};
export const getAllUsersService = async (query: userPageQuery) => {
  const {pageNo = 0, pageSize = 5, ...where} = query;
  const users = await tableRepository.find({
    where: where,
    skip: pageNo * pageSize,
    take: pageSize,
  });
  return Result.success(users);
};

export const loginService = async (loginCode) => {
  const user = await tableRepository.findOneBy({loginCode: loginCode});
  if (user) {
    const token = generateToken({userId: String(user.userId).padStart(8, '0')});
    token && await setRedis(`token_login_${String(user.userId).padStart(8, '0')}`, token, 1000 * 60 * 60 * 7);
    return Result.success({
      userId: user.userId,
      username: user.username,
      token: token,
    }, '登录成功');
  }
  return Result.fail(ResultCode.LOGIN_ERROR, ResultCodeMessages[ResultCode.LOGIN_ERROR]);
};

export const registerService = async (username, password) => {
  const user = await tableRepository.findOneBy({username: username});
  if (user) {
    return Result.fail(ResultCode.USER_EXIST, '用户已存在');
  }
  let md5Pwd = md5(password);
  await tableRepository.save({username, password: md5Pwd});
  return Result.success(null, '注册成功');
};

export const registerServiceByEmail = async (email, password) => {
  const user = await tableRepository.findOneBy({email: email});
  if (user) {
    return Result.fail(ResultCode.USER_EXIST, '用户已存在');
  }
  let md5Pwd = md5(password);
  await tableRepository.save({email, password: md5Pwd});
  return Result.success(null, '注册成功');
}
